<script setup>
import { ref, watch, onBeforeUnmount, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Tab as VanTab, Tabs as VanTabs, Image as VanImage, Search as VanSearch, Icon as VanIcon } from 'vant';
import axios from 'axios';

const route = useRoute();
const router = useRouter();

const value = ref('');
const active = ref(0); // 初始值设为0，表示默认选中“关注”选项卡
const todayMenus = ref([]);

// 加载组件时恢复选项卡状态
onMounted(() => {
  const savedActive = sessionStorage.getItem('activeTab');
  if (savedActive !== null) {
    active.value = parseInt(savedActive, 10);
  } else {
    // 如果没有保存的选项卡状态，且路由中有默认选项卡参数，则使用该参数
    if (route.query.tab) {
      active.value = parseInt(route.query.tab, 10);
    }
  }
});

// 离开组件时保存选项卡状态
onBeforeUnmount(() => {
  sessionStorage.setItem('activeTab', active.value.toString());
});

const fetchTodayMenus = async () => {
  try {
    const response = await axios.get("web/todaymenu/getTodaymenuList");
    console.log('Fetched data:', response.data);
    todayMenus.value = response.data.date;
    todayMenus.value.sort((a, b) => b.popularity - a.popularity);
  } catch (error) {
    console.error('Error fetching today menus:', error);
  }
};

const increasePopularity = async (menu) => {
  try {
    const response = await axios.post("web/todaymenu/increasePopularity", { tid: menu.tid });
    if (response.data.code === 200) {
      menu.popularity += 1;
      todayMenus.value.sort((a, b) => b.popularity - a.popularity);
    } else {
      console.error('点赞失败');
    }
  } catch (error) {
    console.error('Error increasing popularity:', error);
  }
};

watch(active, (newVal) => {
  if (newVal === 1) {
    fetchTodayMenus();
  }
});

const toSearchPage = () => {
  router.push({ name: 'search' });
};
</script>

<template>
  <div>
    <van-search v-model="value" placeholder="搜索食材，菜谱" @click="toSearchPage" />

    <van-tabs v-model:active="active">
      <van-tab title="关注">
        <!-- 关注内容 -->
        <main class="content">
          <van-grid style="margin-top: 20px;display: flex;justify-content: space-around">
            <van-grid-item icon="photograph"  text="写笔记" to="/release"/>
            <van-grid-item icon="invitation" text="新消息" to="/notice"/>
            <van-grid-item icon="comment" text="笔记广场" to="/ground"/>
            <van-grid-item icon="ascending" text="排行榜" to="/leaderboard"/>
          </van-grid>
          <div style="margin-top: 40px;display: flex;align-items: center;justify-content: center;">
            <span style="font-size: 14px;text-indent: 1em;color: darkgray">你还没有关注任何人哦~</span>
          </div>
          <div style="display: flex;align-items: center;justify-content: center;">
            <van-button style="background-color: #F7F8FA;color: black;border-radius: 20px;"size="small" to="/follow">去关注</van-button>
          </div>
          <div style="text-indent: 1em;margin-top: 30px;">
            <span >受欢迎的笔记</span>
          </div>
        </main>
      </van-tab>
      <van-tab title="今日推荐">
        <div v-if="active === 1">
          <div v-for="menu in todayMenus" :key="menu.tid" class="menu-item">
            <van-image
                :src="menu.dishImageUrl"
                width="100%"
                height="200"
                fit="cover"
                class="menu-image"
            />
            <div class="menu-info">
              <div class="top-info">
                <div class="author-section">
                  <img :src="menu.authorImageUrl" alt="作者头像" class="author-image" />
                  <span class="author-name">{{ menu.author }}</span>
                </div>
                <div class="like-section">
                  <span class="popularity">{{ menu.popularity }}</span>
                  <van-icon name="good-job-o" @click="increasePopularity(menu)" class="like-icon" />
                </div>
              </div>
              <div class="description">
                {{ menu.description }}
              </div>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="每周餐单">
        <!-- 每周餐单内容 -->
      </van-tab>
      <van-tab title="会员专属">
        <!-- 会员专属内容 -->
      </van-tab>
    </van-tabs>
  </div>
</template>

<style scoped>
.menu-item {
  margin-bottom: 20px;
}
.menu-image {
  margin-bottom: 10px;
}
.menu-info {
  padding: 10px;
  background-color: #f8f8f8;
}
.top-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.author-section {
  display: flex;
  align-items: center;
}
.author-image {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}
.author-name {
  font-weight: bold;
}
.like-section {
  display: flex;
  align-items: center;
}
.popularity {
  margin-right: 10px;
  font-weight: bold;
}
.like-icon {
  font-size: 20px;
  cursor: pointer;
}
.description {
  margin-top: 10px;
  color: #666;
}
</style>